﻿using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.WebSockets;
using System.Threading.Tasks;
using IntelligentEscalator.BUS;
using IntelligentEscalator.DAL;
using IntelligentEscalator.ElevatorWebSocket;
using IntelligentEscalator.Models;

namespace IntelligentEscalator
{
    public class ElevatorScheduled : IJob
    {
        public ConcurrentDictionary<int, ConcurrentDictionary<string, WebSocket>> _areasockets;
        public static ConcurrentDictionary<int, ConcurrentDictionary<string, WebSocket>> _single_elevatorsockets;
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                _areasockets = ElevatorWebSocketMiddleware._areasockets;
                _single_elevatorsockets = ElevatorWebSocketMiddleware._single_elevatorsockets;

                List<LiftStateALL> list = ElevatorStateBUS.state_list;
                if (list != null && list.Count > 0)
                {
                    for (int k = 0; k < list.Count; k++)
                    {
                        LiftStateALL liftStateALL = new LiftStateALL();
                        liftStateALL = list[k];
                        if (liftStateALL.Elevator_control_status != 99)
                        {
                            DateTime dt2 = Convert.ToDateTime(liftStateALL.UpdateTime);
                            DateTime dt1 = DateTime.Now;
                            TimeSpan ts = dt1.Subtract(dt2);
                            double seconds = ts.TotalSeconds;
                            if (seconds > ElevatorStateBUS.Offline)
                            {
                                LogHelper.Log("设备:" + list[k].opcNO + "最后更新时间:" + liftStateALL.UpdateTime);

                                liftStateALL.Alarm_bell = 0;
                                liftStateALL.CarCall = "0000000000";
                                liftStateALL.Car_load = 0;
                                liftStateALL.Elevator_control_status = 99;
                                liftStateALL.Elevator_running_state = 1;
                                liftStateALL.Elevator_moving_status = 1;
                                liftStateALL.Faults = 0;
                                liftStateALL.Landing_call_respond_down = "0000000000";
                                liftStateALL.Landing_call_respond_up = "0000000000";
                                liftStateALL.Full_load_alarm = 0;
                                liftStateALL.Moving_direction = 2;
                                liftStateALL.Elevator_control_statusName = "离线";
                                liftStateALL.Elevator_control_statusNameEn = "OFL";
                                ElevatorStateBUS bus = new ElevatorStateBUS();
                                bus.UpdateData(liftStateALL.opcNO, liftStateALL);
                                //ElevatorStateBUS.UpdateData(liftStateALL.opcNO, liftStateALL);
                                PushElevatorMessage(liftStateALL.ElevatorID, liftStateALL);
                                bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
                                bool result4 = PushElevatorListMessage("RefreshElevator").Result;

                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("定时查询状态" + ex.ToString());
            }

        }

        private bool PingIp(string strIP)
        {
            bool bRet = false;
            try
            {
                if (!string.IsNullOrEmpty(strIP))
                {
                    Ping pingSend = new Ping();
                    PingReply reply = pingSend.Send(strIP, 1000);
                    if (reply.Status == IPStatus.Success)
                        bRet = true;
                    LogHelper.Log("IP:" + strIP + "PING成功");
                }
                else
                {
                    bRet = false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log("PING功能异常" + ex.ToString());
                bRet = false;
            }
            return bRet;
        }

        public async Task<bool> PushElevatorMessage(int elevatorid, LiftStateALL elevatorState)
        {
            string Msg = JsonConvert.SerializeObject(elevatorState);
            await SendElevatorMessage(elevatorid, Msg);
            return false;
        }

        public async Task SendElevatorMessage(int elevatorid, string Message)
        {
            try
            {
                if (_single_elevatorsockets != null)
                {
                    ConcurrentDictionary<string, WebSocket> _tempsockets;
                    bool getSuccess = _single_elevatorsockets.TryGetValue(elevatorid, out _tempsockets);
                    if (getSuccess)
                    {
                        foreach (var item in _tempsockets)
                        {
                            WebSocket socket = item.Value;
                            if (socket.State.ToString() == "Open")
                            {
                                byte[] bMessage = System.Text.Encoding.UTF8.GetBytes(Message);
                                await socket.SendAsync(new ArraySegment<byte>(bMessage), WebSocketMessageType.Text, true, new System.Threading.CancellationToken());
                            }
                            else
                            {
                                WebSocket tempsocket;
                                _tempsockets.Remove(item.Key, out tempsocket);
                            }
                        }
                        _single_elevatorsockets.TryAdd(elevatorid, _tempsockets);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }

        public async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }

        public async Task<bool> PushElevatorListMessage(string msg)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushElevatorListMessage(msg);
        }
    }
}
